package com.mxl.realm;

import com.alibaba.fastjson.JSON;
import com.mxl.model.Users;
import com.mxl.service.UsersServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.Md5CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义shiro的Realm
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UsersServiceImpl usersService;

    public static void main(String[] args) throws Exception{
        Md5Hash md5Hash = new Md5Hash("mxl");
        System.out.println(md5Hash.toString());
    }

    /**
     * 密码加密方式:改为MD5
     * @return
     */
    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        return new Md5CredentialsMatcher();
    }


    /**
     * 权限认证
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> stringSet = new HashSet<>();
        stringSet.add("user:show");
        stringSet.add("user:admin");
        stringSet.add("user:user");
        info.setStringPermissions(stringSet);
        System.out.println(JSON.toJSONString(stringSet));
        return info;
    }

    /**
     * 身份认证: 从数据库 验证 用户
     *
     * @param token
     * @return AuthorizationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = "";
        Users userByName = usersService.getUserByName(username);
        password = userByName.getPassword();
        //返回从数据库中查询到的用户信息
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
